﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Product;
using BrokerBase.Lib.Tool;
using Broker.Mgr.ViewModel;
using NHibernate;
using BrokerBase.Lib.Core;
using BrokerBase.Lib.Base;
using Broker.View.Comm;
using Telerik.Windows.Controls;
using BrokerBase.Lib.Company;
using BrokerBase.Lib.Product.RateFactorConverter;
using BrokerBase.Lib.Policy;
using Broker.View.PolicyView;
using BrokerBase.Lib.Person;

namespace Broker.View.ProductView
{
    /// <summary>
    /// ProductPage.xaml 的交互逻辑
    /// </summary>
    public partial class ProductPage 
    {

        private IProduct product;
        private bool isImportData;

        private Window owner;

        public ProductPage(IProduct product,Window owner)
        {
            InitializeComponent();
            this.owner = owner;
            this.product = product;

            Loaded += new RoutedEventHandler(ProductForm_Loaded);
            //PreviewClosed += new EventHandler<WindowPreviewClosedEventArgs>(ProductForm_PreviewClosed);
        }

        //void ProductForm_PreviewClosed(object sender, WindowPreviewClosedEventArgs e)
        //{
        //    if (!product.IsCheck && MessageBox.Show("是否要关闭产品窗口?", "提示",MessageBoxButton.YesNo) == MessageBoxResult.No)
        //    {
        //        e.Cancel = true;
        //    }

        //    //TextBlock t;

        //    //t.TextTrimming
            
        //}

        void ProductForm_Loaded(object sender, RoutedEventArgs e)
        {
            LoadCompanies();
            LoadTimeUnit();
            SetOperRight();
            DataContext = product;
            PropertyToView();

            if (LibGlobal.AppType == AppType.Business)
            {
                tabExpress.Visibility = Visibility.Collapsed;
            }
        }

        public Action<IProduct> CallBack { get; set; }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            ViewToProperties();

            this.Cursor = Cursors.Wait;

            try
            {
                if (product.IsCheck)
                {
                    MessageBox.Show("该产品已经审核过,不能保存!", "提示");
                    return;
                }

                ViewToProperty();

                if (product.Id == 0)
                    product.CreateTime = DateTime.Now;
                else
                    product.ModifyTime = DateTime.Now;

                if (Verify())
                {
                    Save(LibGlobal.HbmSessionFactory.GetCurrentSession());
                    MessageBox.Show("保存成功!", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误");
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// 导入费率
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (product.IsCheck)
                {
                    MessageBox.Show("该产品已经审核过,不能再次导入费率表!", "提示");
                    return;
                }

                System.Windows.Forms.OpenFileDialog fileDlg = new System.Windows.Forms.OpenFileDialog();

                fileDlg.Filter = @"Excel文件(*.xlsx)|*.xlsx|Excel 97-2003文件(*.xls)|*.xls";

                fileDlg.Multiselect = false;
                fileDlg.ShowDialog();

                string fileName = fileDlg.FileName;

                if (!string.IsNullOrEmpty(fileName))
                {
                    if (string.IsNullOrEmpty(product.Name))
                    {
                        txtName.Text = System.IO.Path.GetFileNameWithoutExtension(fileName);
                        product.Name = txtName.Text;
                    }

                    ImportUtil imp = new ImportUtil();

                    imp.ImportRate(fileName, this.product);

                    isImportData = true;

                    SetRateGridHeader(product.ColRateFactors, product.RowRateFactors);

                    IList<DisplayRateRow> rows = ProductViewUtil.GetDisplayRateRows(product);

                    gvRate.ItemsSource = rows;

                    SetProductRateFactorAssociation();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误");
            }
            finally
            {
                buyRoot.IsBusy = false;
            }

        }

        private void btnCheck_Click(object sender, RoutedEventArgs e)
        {
            if (product.IsCheck)
            {
                MessageBox.Show("该产品已经审核过,不能再次审核!", "提示");

            }
            else
            {
                ViewToProperty();
                if (Verify())
                {
                    try
                    {
                        product.CheckTime = DateTime.Now;
                        product.CheckerName = "Admin";
                        Save(LibGlobal.HbmSessionFactory.GetCurrentSession());
                        txtCheckTime.Text = DateTime.Now.ToShortDateString();
                        MessageBox.Show("审核成功!", "提示");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "错误提示");
                    }
                }

            }
        }

        private void btnUnCheck_Click(object sender, RoutedEventArgs e)
        {
            if (!product.IsCheck)
            {
                MessageBox.Show("该产品还没有审核过,不能反审核!", "提示");

            }
            else
            {
                try
                {
                    product.CheckTime = null;
                    product.CheckerName = null;
                    Save(LibGlobal.HbmSessionFactory.GetCurrentSession());
                    MessageBox.Show("反审核成功!", "提示");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "错误提示");
                }
            }
        }

        private void btnDocFlod_Click(object sender, RoutedEventArgs e)
        {
            string path =LibGlobal.GetAppPath()+  @"\产品介绍\" +product.Company.Name + @"\" + product.Name;
            System.Diagnostics.Process.Start("explorer.exe", path);
        }

        //private void btnExit_Click(object sender, RoutedEventArgs e)
        //{
        //    Close();
        //}

        private void PropertyToView()
        {
            //txtDescription.Document = CreateFormattedDocument(product.Description);

            if (product.ProductType == ProductType.Basic)
            {
                rbtBasic.IsChecked = true;
            }
            else
            {
                rbtExtra.IsChecked = true;
                gvRelation.ItemsSource = product.Relations;
            }
            
            if (product.RateType == RateType.Premium)
                rbtPremium.IsChecked = true;
            else
                rbtAmount.IsChecked = true;

            if (product.UnitType == UnitType.Amt)
                rbtUnitTypeAmt.IsChecked = true;
            else
                rbtUnitTypeQty.IsChecked = true;

            string s = string.Empty;
            foreach (var pp in product.PaymentPeriods)
            {
                s += pp.Name + ";";             
            }
            txtPayPeriod.Text = s;



            s=string.Empty;
            foreach (var ip in product.InsurancePeriods)
            {
                s += ip.Name + ";";
            }
            txtInsPeriod.Text = s;

            s = string.Empty;
            foreach (var tu in product.PaymentCycles)
            {
                s += tu.Name + ";";
            }
            txtPayType.Text = s;

            //if (product.ProductType == ProductType.Basic)
            //    tabRelation.Visibility = Visibility.Hidden;

        }

        private void ViewToProperties()
        {
            if (rbtUnitTypeQty.IsChecked == true)
                product.UnitType = UnitType.Qty;
            else
                product.UnitType = UnitType.Amt;

            if (rbtAmount.IsChecked == true)
                product.RateType = RateType.Amount;
            else
                product.RateType = RateType.Premium;
        }

        
        /// <summary>
        /// 保存
        /// </summary>
        private void Save(ISession sess)
        {

            buyRoot.IsBusy = true;
            try
            {
                if (product.ExpandExpress != null && string.IsNullOrEmpty(product.ExpandExpress.Code))
                {
                    product.ExpandExpress = null;
                }

                if (product.ProductType == ProductType.Basic)
                {
                    BaseService<BasicProduct> svr = new BaseService<BasicProduct>(sess);

                    svr.SaveOrUpdate(product as BasicProduct);
                }
                else
                {
                    BaseService<ExtraProduct> svr = new BaseService<ExtraProduct>(sess);

                    svr.SaveOrUpdate(product as ExtraProduct);
                }

                if (CallBack != null)
                    CallBack(product);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

                buyRoot.IsBusy = false;
            }
        }

        

        /// <summary>
        /// 选择付款方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelPayType_Click(object sender, RoutedEventArgs e)
        {
            IBaseService<TimeUnit> svr = new BaseService<TimeUnit>(LibGlobal.HbmSessionFactory.GetCurrentSession());

            IList<TimeUnit> ls = svr.GetListByHQL("from TimeUnit");

            ListSelForm frm=new ListSelForm();
            
            GridViewDataColumn col1=new GridViewDataColumn();
            col1.Header="名称";
            col1.Width=new GridViewLength(120,GridViewLengthUnitType.Star);
            col1.DataMemberBinding=new Binding("Name");
            frm.gvList.Columns.Add(col1);

            frm.Owner = this.owner;
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Width = 200;
            frm.Height = 300;

            IList<ITimeUnit> result = frm.MultiSelecteByList<TimeUnit>(ls).Cast<ITimeUnit>().ToList<ITimeUnit>();

            result = result.OrderBy(p => p.Id).ToList<ITimeUnit>();
            string tus=string.Empty;

            foreach (ITimeUnit tu in result)
            {
                tus += tus == string.Empty ? tu.Name : ";" + tu.Name;
            }

            product.PaymentCycles = result;
            txtPayType.Text = tus;
        }



        /// <summary>
        /// 设置费率表头
        /// </summary>
        /// <param name="colFactors"></param>
        /// <param name="rowFactors"></param>
        private void SetRateGridHeader(IList<IRateFactor> colFactors, IList<IRateFactor> rowFactors)
        {
            int count = colFactors[0].Items.Split(';').Count();

            StackPanel[] spfs = new StackPanel[] { new StackPanel(), new StackPanel(), new StackPanel() };//固定3个列

            spfs[0].Orientation = Orientation.Vertical;
            spfs[1].Orientation = Orientation.Vertical;
            spfs[2].Orientation = Orientation.Vertical;

            StackPanel[] sps = new StackPanel[count];

            for (int row = 0; row < colFactors.Count;row++ )
            {
                IRateFactor rf = colFactors[row];

                string[] items = rf.Items.Split(';');

                for (int i = 0; i < count; i++)
                {
                    if (sps[i] == null)
                    {
                        sps[i] = new StackPanel();
                        sps[i].Orientation = Orientation.Vertical;
                    }

                    TextBlock tb = new TextBlock();
                    tb.HorizontalAlignment = HorizontalAlignment.Center;
                    tb.Text = items[i];

                    sps[i].Children.Add(tb);
                }

                TextBlock tb1 = new TextBlock();

                string s = rowFactors[0].Name.Contains("Empty") ? null : rowFactors[0].Name;
                tb1.Text = row == colFactors.Count - 1 ? s : string.Empty;// rowFactors[0].Name.Contains("Empty") ? null : rowFactors[0].Name; //row == colFactors.Count - 1 ? rowFactors[0].Name : string.Empty;

                spfs[0].Children.Add(tb1);

                TextBlock tb2 = new TextBlock();
                s = rowFactors[1].Name.Contains("Empty") ? null : rowFactors[1].Name;
                tb2.Text = row == colFactors.Count - 1 ? s : string.Empty;
                spfs[1].Children.Add(tb2);

                TextBlock tbh = new TextBlock();
                tbh.Text = rf.Name;
                spfs[2].Children.Add(tbh);
            }

            gvRate.Columns.Clear();
            //gvRate.ItemsSource = null;

            GridViewDataColumn col1 = new GridViewDataColumn();
            col1.Header = spfs[0];
            col1.DataMemberBinding = new Binding("Key1");

            gvRate.Columns.Add(col1);

            GridViewDataColumn col2 = new GridViewDataColumn();
            col2.Header = spfs[1];
            col2.DataMemberBinding = new Binding("Key2");
            gvRate.Columns.Add(col2);

            GridViewDataColumn colh = new GridViewDataColumn();
            colh.Header = spfs[2];
            gvRate.Columns.Add(colh);

            for (int i = 0; i < count; i++)
            {
                GridViewDataColumn col = new GridViewDataColumn();
                col.Header = sps[i];
                Binding bind=new Binding(string.Format("Rates[{0}]",i));
                col.DataMemberBinding = bind;
                col.DataFormatString = "F2";
                col.MinWidth = 50;
                col.MaxWidth = 100;
                col.TextAlignment = TextAlignment.Right;
                
                gvRate.Columns.Add(col);
            }

        }

        private void btnAuxAdd_Click(object sender, RoutedEventArgs e)
        {
            AuxProperty aux = new AuxProperty(this.product);

            AuxPropertyForm frm = new AuxPropertyForm(aux);

            frm.Owner = this.owner;
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.CallBack = (IAuxProperty ap) =>
            {
                product.AuxProperties.Add(ap);
                gvAux.ItemsSource = null;
                gvAux.ItemsSource = product.AuxProperties;
            };
            frm.Show();

        }

        private void btnAuxEdit_Click(object sender, RoutedEventArgs e)
        {
            ViewAux();
        }

        private void gvAux_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewAux();
        }

        private void ViewAux()
        {
            IAuxProperty aux = gvAux.SelectedItem as IAuxProperty;

            if (aux != null)
            {
                AuxPropertyForm frm = new AuxPropertyForm(aux);
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = this.owner;

                frm.CallBack = (IAuxProperty ap) =>
                {
                    gvAux.ItemsSource = null;
                    gvAux.ItemsSource = product.AuxProperties;
                };
                frm.Show();
            }
        }

        private void btnAuxDel_Click(object sender, RoutedEventArgs e)
        {
            
            IAuxProperty aux = gvAux.SelectedItem as IAuxProperty;

            if (aux != null)
            {
                if (MessageBox.Show("是否要删除" + aux.Name, "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    product.AuxProperties.Remove(aux);
                    gvAux.ItemsSource = null;
                    gvAux.ItemsSource = product.AuxProperties;
                }
            }
        }

        private void btnDutyAdd_Click(object sender, RoutedEventArgs e)
        {
            IDuty duty = new Duty(product);

            DutyForm frm = new DutyForm(duty);

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = this.owner;

            frm.CallBack = (IDuty d) =>
                {
                    product.Duties.Add(d);
                    gvDuty.ItemsSource = null;
                    gvDuty.ItemsSource = product.Duties;
                };

            frm.Show();

        }

        private void btnDutyEdit_Click(object sender, RoutedEventArgs e)
        {
            ViewDuty();
        }

        private void btnDutyDel_Click(object sender, RoutedEventArgs e)
        {
            IDuty duty = gvDuty.SelectedItem as IDuty;

            if (duty != null)
            {
                if (MessageBox.Show(string.Format("是否要删除:{0}", duty.Name), "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    product.Duties.Remove(duty);
                    gvDuty.ItemsSource = null;
                    gvDuty.ItemsSource = product.Duties;
                }
            }
        }

        private void gvDuty_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewDuty();
        }

        private void ViewDuty()
        {
            IDuty duty = gvDuty.SelectedItem as IDuty;

            if (duty != null)
            {
                DutyForm frm = new DutyForm(duty);
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = this.owner;

                frm.CallBack = (IDuty d) =>
                    {
                        gvDuty.ItemsSource = null;
                        gvDuty.ItemsSource = product.Duties;
                    };
                frm.Show();
            }
        }

        private void SetProductRateFactorAssociation()
        {
            foreach (var colRf in product.ColRateFactors)
            {
                if (colRf.IsHasConverter && colRf.ConverterInstance.IsToPropertiesEnable)
                    colRf.ConverterInstance.ToProperties();
            }

            foreach (var rowRf in product.RowRateFactors)
            {
                if (rowRf.IsHasConverter && rowRf.ConverterInstance.IsToPropertiesEnable)
                    rowRf.ConverterInstance.ToProperties();
            }

            if(product.IsPaymentPeriodsFromFixRate)
            {
                string payperiods=string.Empty;

                foreach(IPaymentPeriod pp in product.PaymentPeriods)
                {
                    payperiods+=payperiods==string.Empty?pp.Name:";"+pp.Name;
                }

                txtPayPeriod.Text = payperiods;
                txtPayPeriod.IsReadOnly = true;
            }

            if (product.IsInsurancePeriodsFromFixRate)
            {
                string insPeriods = string.Empty;

                foreach (IInsurancePeriod pp in product.InsurancePeriods)
                {
                    insPeriods += insPeriods == string.Empty ? pp.Name : ";" + pp.Name;
                }

                txtInsPeriod.Text = insPeriods;
                txtInsPeriod.IsReadOnly = true;
            }

            if (product.UnitType == UnitType.Amt)
                rbtUnitTypeAmt.IsChecked = true;
            else
                rbtUnitTypeQty.IsChecked = true;
        }

        private void btnAddRelation_Click(object sender, RoutedEventArgs e)
        {
            IExtraProduct exp = (IExtraProduct)product;

            if (exp.Company == null)
            {
                MessageBox.Show("请先选择保险公司!", "提示");
                return;

                
            }

            IRelation relation = new Relation();

            if (product.ProductType == ProductType.Extra)
                relation.Extra = product as IExtraProduct;
            else
                relation.Basic = product as IBasicProduct;

            relation.IsTerminationEqualBasic = true;
            relation.PeriodConstraint = PeriodConstraintType.LessOrEqual;

            RelationForm frm = new RelationForm(relation,product);

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = this.owner;

            frm.CallBack = (IRelation r) =>
            {
                exp.Relations.Add(r);

                gvRelation.ItemsSource = null;
                gvRelation.ItemsSource = exp.Relations;
            };

            frm.Show();

        }

        private void btnBatchAddRelation_Click(object sender, RoutedEventArgs e)
        {
            if (product.Company == null)
            {
                MessageBox.Show("请先选择保险公司!", "提示");
                return;
            }

            ProductType pType = product.ProductType;


            if (pType == ProductType.Extra)
            {
                IBaseService<BasicProduct> svr = new BaseService<BasicProduct>(LibGlobal.HbmSessionFactory.GetCurrentSession());

                IList<IBasicProduct> ls = svr.GetListByHQL(string.Format("from BasicProduct as p where  p.Company.Id={0} Order by p.Name", product.Company.Id)).Cast<IBasicProduct>().ToList<IBasicProduct>();

                ListSelForm frm = new ListSelForm();
                frm.Owner = this.owner;
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                GridViewDataColumn col1 = new GridViewDataColumn();
                col1.Header = "名称";
                col1.Width = new GridViewLength(200, GridViewLengthUnitType.Star);
                col1.DataMemberBinding = new Binding("Name");

                frm.gvList.Columns.Add(col1);

                IList<IBasicProduct> bps = frm.MultiSelecteByList<IBasicProduct>(ls);

                foreach (IBasicProduct bp in bps)
                {


                    IRelation rel = new Relation();
                    rel.Basic = bp;
                    rel.Extra = this.product as IExtraProduct;
                    rel.PeriodConstraint = PeriodConstraintType.LessOrEqual;
                    rel.IsTerminationEqualBasic = true;

                    if (this.product.Relations.FirstOrDefault(p => p.Basic.Name == bp.Name) == null)
                    {
                        this.product.Relations.Add(rel);
                    }
                }
            }
            else
            {
                IBaseService<ExtraProduct> svr = new BaseService<ExtraProduct>(LibGlobal.HbmSessionFactory.GetCurrentSession());

                IList<IExtraProduct> ls = svr.GetListByHQL(string.Format("from ExtraProduct as p where  p.Company.Id={0} Order by p.Name", product.Company.Id)).Cast<IExtraProduct>().ToList<IExtraProduct>();

                ListSelForm frm = new ListSelForm();
                frm.Owner = this.owner;
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                GridViewDataColumn col1 = new GridViewDataColumn();
                col1.Header = "名称";
                col1.Width = new GridViewLength(200, GridViewLengthUnitType.Star);
                col1.DataMemberBinding = new Binding("Name");

                frm.gvList.Columns.Add(col1);

                IList<IExtraProduct> eps = frm.MultiSelecteByList<IExtraProduct>(ls);


                foreach (IExtraProduct ep in eps)
                {
                    IRelation rel = new Relation();
                    rel.Basic = this.product as IBasicProduct;
                    rel.Extra = ep;
                    rel.PeriodConstraint = PeriodConstraintType.LessOrEqual;
                    rel.IsTerminationEqualBasic = true;

                    if (this.product.Relations.FirstOrDefault(p => p.Extra.Name==ep.Name)==null)
                    {
                        this.product.Relations.Add(rel);
                    }
                }

            }

            gvRelation.ItemsSource = null;
            gvRelation.ItemsSource = product.Relations;

        }

        private void btnEditRelation_Click(object sender, RoutedEventArgs e)
        {
            ViewRelation();
        }

        private void ViewRelation()
        {
            IRelation rel = gvRelation.SelectedItem as IRelation;

            if (rel != null)
            {
                RelationForm frm = new RelationForm(rel,product);
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = this.owner;

                frm.CallBack = (IRelation r) =>
                {
                    gvRelation.ItemsSource = null;
                    gvRelation.ItemsSource = product.Relations;
                };

                frm.Show();

            }
        }

        private void gvRelation_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewRelation();
        }

        private void btnDelRelation_Click(object sender, RoutedEventArgs e)
        {
            IRelation rel=gvRelation.SelectedItem as IRelation;

            if(rel !=null)
            {
                if (MessageBox.Show(string.Format("是否要删除关联的主险:{0}", rel.Basic.Name), "提示",MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    IExtraProduct exp = product as IExtraProduct;

                    exp.Relations.Remove(rel);

                    gvRelation.ItemsSource = null;
                    gvRelation.ItemsSource = exp.Relations;
                }
            }
        }

        private void btnBasicAmountEdit_Click(object sender, RoutedEventArgs e)
        {
            IBasicAmount ba=gvBasicAmount.SelectedItem as IBasicAmount;

            if(ba!=null)
            {

                BasicAmountForm frm = new BasicAmountForm(ba);
                frm.Owner = this.owner;
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                frm.CallBack = (IBasicAmount b) =>
                    {
                        gvBasicAmount.ItemsSource = null;
                        gvBasicAmount.ItemsSource = product.BasicAmounts;
                    };

                frm.Show();

            }
        }

        private void LoadTimeUnit()
        {
            IBaseService<TimeUnit> svr = new BaseService<TimeUnit>(LibGlobal.HbmSessionFactory.GetCurrentSession());

            IList<ITimeUnit> ls = svr.GetListByHQL("from TimeUnit").Cast<ITimeUnit>().ToList<ITimeUnit>();

            cmbUnit.ItemsSource = ls;
        }

        private void LoadCompanies()
        {
            IBaseService<Company> svr=new BaseService<Company>(LibGlobal.HbmSessionFactory.GetCurrentSession());

            IList<ICompany> ls = svr.GetListByHQL("from Company").Cast<ICompany>().ToList<ICompany>();

            cmbCompany.ItemsSource = ls;
        }

        private void btnAdjAdd_Click(object sender, RoutedEventArgs e)
        {
            IAdjustRate adj=new AdjustRate(product);

            AdjustRateForm frm = new AdjustRateForm(adj);

            frm.Owner = this.owner;
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            frm.CallBack = (IAdjustRate a) =>
                {
                    product.AdjustRates.Add(a);

                    gvAdj.ItemsSource = null;
                    gvAdj.ItemsSource = product.AdjustRates;
                };

            frm.Show();
        }

        private void btnAdjEdit_Click(object sender, RoutedEventArgs e)
        {
            RadGridView r;

            DataGridTextColumn d;

            

            ViewAdjRate();
        }

        private void gvAdj_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewAdjRate();
        }

        private void ViewAdjRate()
        {
            IAdjustRate adj = gvAdj.SelectedItem as IAdjustRate;

            if (adj != null)
            {
                AdjustRateForm frm = new AdjustRateForm(adj);

                frm.Owner = this.owner;
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                frm.CallBack = (IAdjustRate a) =>
                {
                    gvAdj.ItemsSource = null;
                    gvAdj.ItemsSource = product.AdjustRates;
                };
                frm.Show();
            }
        }

        private void btnAdjDel_Click(object sender, RoutedEventArgs e)
        {
            IAdjustRate adj = gvAdj.SelectedItem as IAdjustRate;

            if (adj != null)
            {
                if (MessageBox.Show("是否要删除" + adj.Name, "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {

                    product.AdjustRates.Remove(adj);
                    gvAdj.ItemsSource = null;
                    gvAdj.ItemsSource = product.AdjustRates;

                }
            }
        }


        private bool ViewToProperty()
        {
            try
            {
                if(!product.IsPaymentPeriodsFromFixRate)
                    PaymentPeriodConverter.CreateProperties(product, txtPayPeriod.Text.Trim().Split(';'));
                if(!product.IsInsurancePeriodsFromFixRate)
                    InsurancePeriodConverter.CreateProperties(product, txtInsPeriod.Text.Trim().Split(';'));

                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);

                return false;
            }
        }

        private bool Verify()
        {
            if (product.Company == null)
            {
                MessageBox.Show("请选择保险公司", "提示");
                return false;
            }

            if(string.IsNullOrEmpty(product.Name))
            {
                MessageBox.Show("请输入产品名称", "提示");
                return false;
            }
            else
            {
                if (product.Id == 0)//id=0表示是新增的商品，需要检查名称是否有重复的
                {
                    ISession sess = LibGlobal.HbmSessionFactory.GetCurrentSession();
                    IList<string> pName = sess.CreateQuery("select Name from Product as p where p.Name='" + product.Name.Trim() + "'").List<string>();

                    if (pName.Count > 0)
                    {
                        MessageBox.Show("产品名称:" + product.Name + " 已存在!");
                        return false;
                    }
                }
            }

            if (string.IsNullOrEmpty(product.Catalog))
            {
                MessageBox.Show("请输入产品分类", "提示");
                return false;
            }

            if (product.PaymentPeriods.Count==0)
            {
                MessageBox.Show("请输入付款期限", "提示");
                return false;
            }

            if (txtPayPeriod.Text == "等于主险" && product.ProductType==ProductType.Basic)
            {
                MessageBox.Show("只有附加险可以设置付款期限[等于主险]", "提示");
                return false;
            }

            if (product.InsurancePeriods.Count == 0)
            {
                MessageBox.Show("请输入保险期限", "提示");
                return false;
            }

            if (txtInsPeriod.Text.Contains("等于主险") && product.ProductType == ProductType.Basic)
            {
                MessageBox.Show("只有附加险可以设置保险期限[等于主险]", "提示");
                return false;
            }

            if (txtInsPeriod.Text.Contains("等于付款期限") && txtPayPeriod.Text.Contains("等于保险期限"))
            {
                MessageBox.Show("付款期限和保险期限不能循环引用！", "提示");
                return false;
            }

            if (product.PaymentCycles.Count==0)
            {
                MessageBox.Show("请选择付款方式", "提示");
                return false;
            }

            if (product.PaymentCycles.FirstOrDefault(p => p.Id == product.TimeUnit.Id) == null)
            {
                MessageBox.Show("付款方式必须包含费率时间单位!", "提示");
                return false;
            }

            if (product.BasicAmounts.Count==0)
            {
                MessageBox.Show("请输入基本保额", "提示");
                return false;
            }

            if (product.ProductType==ProductType.Basic && product.RateRows.Count==0)
            {
                MessageBox.Show("请导入费率", "提示");
                return false;
            }

            if (product.ProductType == ProductType.Extra)
            {
                IExtraProduct exp = product as IExtraProduct;

                if (exp.Relations.Count == 0)
                {
                    MessageBox.Show("附加险必须关联主险", "提示");
                    return false;
                }
            }

            if (!ExpressTest())
            {

                MessageBox.Show("表达式编译错误!", "提示");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 固定费率页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabFixRate_Loaded(object sender, RoutedEventArgs e)
        {
            SetRateGridHeader(product.ColRateFactors, product.RowRateFactors);
            IList<DisplayRateRow> rows = ProductViewUtil.GetDisplayRateRows(product);
            gvRate.ItemsSource = rows;
        }

        private void tabAdjRate_Loaded(object sender, RoutedEventArgs e)
        {
            gvAdj.ItemsSource = product.AdjustRates;
            
        }

        private void tabBasicAmount_Loaded(object sender, RoutedEventArgs e)
        {
            gvBasicAmount.ItemsSource = product.BasicAmounts;
        }

        private void tabRelation_Loaded(object sender, RoutedEventArgs e)
        {
            if (product.ProductType == ProductType.Basic)
            {
                gvRelation.Columns[0].IsVisible = false;
            }
            else
            {
                gvRelation.Columns[1].IsVisible = false;
            }
            gvRelation.ItemsSource = product.Relations;
        }

        private void tabDuty_Loaded(object sender, RoutedEventArgs e)
        {
            gvDuty.ItemsSource = product.Duties;
        }

        private void tabAuxProperty_Loaded(object sender, RoutedEventArgs e)
        {
            gvAux.ItemsSource = product.AuxProperties;
        }

        
        /// <summary>
        /// 表达式测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            ExpressTest();
        }

        private bool ExpressTest()
        {
            string result = string.Empty;

            bool success = false;


            if (string.IsNullOrEmpty(txtExpandExpress.Text))
            {
                product.ExpandExpress = null;
                success = true;
            }
            else
            {
                if (product.ExpandExpress == null)
                    product.ExpandExpress = new ExpandExpress();

                product.ExpandExpress.Code = txtExpandExpress.Text;
            }

            if(product.ExpandExpress!=null)
                success = product.ExpandExpress.Compile(out result);

            txtCompileInfo.Text = result;

            return success;
        }

        private void SetOperRight()
        {
            btnSave.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
            btnImport.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
            btnCheck.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
            btnUnCheck.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
        }

        private void btnExpressTest_Click(object sender, RoutedEventArgs e)
        {
            ExpressTest();
        }

        private void btnExpressTemplate_Click(object sender, RoutedEventArgs e)
        {
            bool isOpen = false;

            try
            {

                if (!string.IsNullOrEmpty(product.ExpandExpress.Code))
                {
                    if (MessageBox.Show("是否要重新打开模板,现有的代码将会被覆盖!", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        isOpen = true;
                    }
                }
                else
                {
                    isOpen = true;
                }

                if (isOpen)
                {
                    string code = ProductUtil.LoadExpandExpressTemplate();

                    product.ExpandExpress.Code = code;
                    txtExpandExpress.Text = code;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message+Environment.NewLine+ex.StackTrace, "提示");
            }
        }

        private void tabExpress_Loaded(object sender, RoutedEventArgs e)
        {
            if (product.ExpandExpress == null)
                product.ExpandExpress = new ExpandExpress();

            Binding bind = new Binding("ExpandExpress.Code");
            bind.Mode = BindingMode.TwoWay;
            txtExpandExpress.SetBinding(TextBox.TextProperty, bind);

        }

        private void btnFast_Click(object sender, RoutedEventArgs e)
        {
            IScheme scheme = new Scheme();
            scheme.BizDate = DateTime.Now;
            scheme.CreateDate = DateTime.Now;

            SexType defaultSex = LibGlobal.GetClientCfg().DefaultSex == "男" ? SexType.Male : SexType.Fmale;

            scheme.HolderSex = defaultSex;
            scheme.HolderAge = PersonUtil.GetAgeFromBirthdayAndTime(LibGlobal.GetClientCfg().DefaultBirthday, DateTime.Now);

            scheme.InsurantSex = defaultSex;
            scheme.InsurantAge = PersonUtil.GetAgeFromBirthdayAndTime(LibGlobal.GetClientCfg().DefaultBirthday, DateTime.Now);

            IPolicyLight pl = new PolicyLight(scheme, new Policy(scheme, ProductType.Basic));
            //pl.Policy.Product = this.product;

            scheme.PolicyLights.Add(pl);

            Scheme2Form frm = new Scheme2Form(scheme,SchemeType.Fast,this.product);

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = LibGlobal.MainWindow;
            frm.Show();
        }

    }
}
